package com.JavaNet.chapter5_url;

import java.io.*;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-19
 *
 * 使用 Authenticator 类设置账号密码 连接http 服务器, 免去了 在浏览器 输入账号密码的步骤
 *
 *
 */
public class AuthenticatorDemo {


    static final String urlString = "http://localhost:8161/admin/index.jsp";


    protected static class MyAuthenticator extends Authenticator {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication ("admin", "admin".toCharArray());
        }
    }


    /**
     * 没有账号密码认证, 则出现: Exception in thread "main" java.io.IOException: Server returned HTTP response code:
     *  401 for URL: http://localhost:8161/admin/index.jsp
     * */
    public static void main(String[] args) throws IOException {


        Authenticator.setDefault (new MyAuthenticator ());
        URL url = new URL (urlString);
        InputStream content = (InputStream)url.getContent();
        BufferedReader in = new BufferedReader (new InputStreamReader(content));
        String line;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        while ((line = in.readLine()) != null) {
            pw.println (line);
        }

        System.out.println("sw.toString() = " + sw.toString());


    }





}
